package com.webserver.http;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 发送响应
 * 该类的每一个实例用于表示HTTP协议规定的响应。
 * 一个响应由三部分构成:状态行，响应头，响应正文。
 *
 * @author XingHaiYang
 * @date 2022/9/19 10:18
 */
public class HttpServletResponse {
    private static MimetypesFileTypeMap mime = new MimetypesFileTypeMap();
    //定义s对象，statusCode响应码，statusReason响应状态
    private Socket s;
    private Integer statusCode = 200;
    private String statusReason = "OK";
    //响应正文相关信息
    private File contentFile;//响应正文对应的实体文件
    private Map<String, String> headers = new HashMap<>();

    // 构造器，给s赋值
    public HttpServletResponse(Socket s) {
        this.s = s;
    }

    //发送响应
    public void response() throws IOException {
        sendStatusLine();
        sendHeaders();
        sendContent();
    }

    //发送响应正文
    private void sendContent() throws IOException {
        OutputStream out = s.getOutputStream();
        if (contentFile!=null) {
            try(
                    FileInputStream fis = new FileInputStream(contentFile);
            ) {
                byte[] data = new byte[1024 * 10];
                int len;
                while ((len = fis.read(data)) != -1) {
                    out.write(data, 0, len);
                }
            }
        }
    }

    //发送响应头
    private void sendHeaders() throws IOException {
        Set<Map.Entry<String, String>> entries = headers.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            println(key + ": " + value);
        }
        //单独发送回车+换行表达响应头发送完毕
        println("");
    }

    //发送状态行
    private void sendStatusLine() throws IOException {
        println("HTTP/1.1" + " " + statusCode + " " + statusReason);
    }

    // 定义输出的方法
    private void println(String line) throws IOException {
        OutputStream out = s.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }

    // get/set方法
    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        addHeader("Content-Type", mime.getContentType(contentFile));
        addHeader("Content-Length", contentFile.length() + "");
    }

    /**
     * 添加一个响应头
     *
     * @param name  响应头的名字
     * @param value 响应头的值
     */
    public void addHeader(String name, String value) {
        headers.put(name, value);
    }

    /**
     * 重定向到指定路径
     *
     * @param location
     */
    public void sendRedirect(String location) {
        /*
            重定向的响应要求:
            1:状态代码为302
            2:包含一个响应头Location，用于指定要求浏览器重定向的路径
         */
        statusCode = 302;
        statusReason = "Moved Temporarily";

        addHeader("Location", location);

    }
}
